package com.itzyf.pokemondata.activity.setting

import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.view.Menu
import android.view.MenuItem
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.MainActivity
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_font.*


class FontActivity : BaseActivity() {
    private var fontSizeScale = 0f
    private var defaultPos = 0
    override fun getContentViewId() = R.layout.activity_font

    override fun getToolbarTitle() = "字体大小"

    override fun handlerActivity() {

        fsvFontSize.setChangeCallbackListener { position ->
            //根据position 获取字体倍数
            fontSizeScale = (0.875 + 0.125 * position).toFloat()
//            sp.edit().putFloat("FONT_SCALE", fontSizeScale).apply()
            //改变当前页面大小
            changeTextSize()
        }

        val scale = sp.getFloat("FONT_SCALE", 0.0f)
        defaultPos = if (scale > 0.5) {
            ((scale - 0.875) / 0.125).toInt()
        } else {
            1
        }

        //注意： 写在改变监听下面 —— 否则初始字体不会改变
        fsvFontSize.setDefaultPosition(defaultPos)
    }

    private fun changeTextSize() {
        txt1.textSize = fontSizeScale * 16
        txt2.textSize = fontSizeScale * 16
        txt3.textSize = fontSizeScale * 14
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.save2, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.action_save) {
            sp.edit().putFloat("FONT_SCALE", fontSizeScale).apply()
            val intent = Intent(this, MainActivity::class.java)
            intent.putExtra("EXIT_TAG", "SINGLETASK")
            startActivity(intent)
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 重新配置缩放系数
     * @return
     */
    override fun getResources(): Resources? {
        val res: Resources = super.getResources()
        val config: Configuration = res.configuration
        config.fontScale = 1f //1 设置正常字体大小的倍数
        res.updateConfiguration(config, res.displayMetrics)
        return res
    }
}